﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WeiTalk.OAuth;
using RestSharp;
using WeiTalk.Interfaces.Sina;
using WeiTalk.SinaEntities.User;
using WeiTalk.Controls;
using System.Windows.Media.Imaging;
using WeiTalk.SinaEntities.Search;

namespace WeiTalk
{
    public partial class PeoplePage : PhoneApplicationPage
    {
        double width = 0d;
        double gap = 5d;
        Button btnGetMore = null;
        int cursor = 0;
        PullAndDownControl reflashControl = new PullAndDownControl();
        StackPanel spGetMore = new StackPanel();
        string locker = "";
        bool isUpdating = false;
        public PeoplePage()
        {
            InitializeComponent();
            width = System.Windows.Application.Current.Host.Content.ActualWidth;
            tbSearch.Width = width - btnSearch.Width;
        }

        private void EnableRefreshControl()
        {
            if (!spPeople.Children.Contains(reflashControl))
            {
                reflashControl.Busy = true;
                reflashControl.EnableImage = false;
                reflashControl.Text = "";
                spPeople.Children.Add(reflashControl);
            }
        }

        private void ResetRefreshControl()
        {
            if (spPeople.Children.Contains(reflashControl))
            {
                spPeople.Children.Remove(reflashControl);
            }
            if (spPeople.Children.Contains(spGetMore))
            {
                spPeople.Children.Remove(spGetMore);
            }
        }

        private void People_Loaded(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(Utility.AccessToken.UID))
            {
                throw new ArgumentNullException("ID 为空.");
            }
            
            btnGetMore = new Button();
            spGetMore.Children.Add(btnGetMore);
            btnGetMore.FontSize = 18.667d;
            btnGetMore.FontWeight = FontWeights.Bold;
            btnGetMore.BorderThickness = new Thickness(0d);
            btnGetMore.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
            btnGetMore.Click += new RoutedEventHandler(GetMorePeople_Click);
           
            GetPeople();
            
        }

        private void GetPeople()
        {
            var client = new RestClient();
            FriendshipsAPI friends = new FriendshipsAPI(client);
            EnableRefreshControl();
            friends.GetFriends(
                (result) =>
                {
                    try
                    {
                        List<Entity> people = result.Data.Users;
                        AddPeopleControl(people);
                        cursor = result.Data.NextCursor;
                    }
                    catch
                    {
                        WeiBoUtility.ShowToast("获取数据异常,请重试...");
                    }

                },
            Utility.AccessToken.UID, null, cursor);
        }

        private void GetPeopleByName(string screnName)
        {
            var client = new RestClient();
            SearchAPI search = new SearchAPI(client);
            spPeople.Children.Clear();
            EnableRefreshControl();
            search.GetAtUser((users) => {
                WeiTalk.SinaEntities.Search.AtUsers theUsers = users.Data;
                AddPeopleControl(theUsers);
            },  screnName);
        }

        private void NoData()
        {
            TextBlock tb = new TextBlock { Text = "没有相关数据..." };
            tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            tb.Margin = new Thickness(0, 50, 0, 0);
            tb.FontSize = 18d;
            tb.FontStyle = System.Windows.FontStyles.Italic;
            spPeople.Children.Add(tb);
        }

        private void AddPeopleControl(WeiTalk.SinaEntities.Search.AtUsers users)
        {
            if (users != null)
            {
                if (users.WeiTalk.Count == 0)
                {
                    //WeiBoUtility.ShowToast("没有相关用户信息...");
                    ResetRefreshControl();
                    NoData();
                    return;
                }
                spPeople.Children.Clear();

                var client = new RestClient();
                UserAPI userApi = new UserAPI(client);
                List<Entity> people = new List<Entity>();
                int finishedCounter = 0;
                foreach (AtUser user in users.WeiTalk)
                {
                    userApi.GetShow(theUser => {
                       lock (people)
                       {
                           people.Add(theUser.Data);
                           finishedCounter++;
                           if (finishedCounter == users.WeiTalk.Count)
                           {
                               AddPeopleControl(people);
                               cursor = 0;
                           }
                       }
                    }, user.UID);
                }
            }
        }

        private void AddPeopleControl(List<Entity> people)
        {
            if (isUpdating)
            {
                return;
            }
            int index = 0;
            StackPanel sp = null;
            isUpdating = true;
            if (people.Count > 0)
            {
                btnGetMore.Content = "正在获取数据...";
                EnableRefreshControl();
            }
            else
            {
                btnGetMore.Content = "点击获取更多...";
                ResetRefreshControl();
                isUpdating = false;
                return;
            }
            Dispatcher.BeginInvoke(() =>
            {
                lock (locker)
                {
                    foreach (var p in people)
                    {
                        if (index % 2 == 0)
                        {
                            sp = new StackPanel();
                            sp.Orientation = System.Windows.Controls.Orientation.Horizontal;
                        }
                        PeopleControl control = new PeopleControl();
                        control.Name = Guid.NewGuid().ToString();
                        control.Id = p.ID;
                        control.Width = width / 2d - gap;
                        control.Name = p.Name;
                        control.ScreenName = p.ScreenName;
                        control.CreateAt = p.CreatedAt;
                        control.FollowMe = p.FollowMe;
                        WeiBoUtility.RetrieveImage(p.ProfileImageUrl,
                            (s) =>
                            {
                                BitmapImage bi = new BitmapImage();
                                bi.SetSource(s);
                                bi.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                                control.headImg.Source = bi;

                            }, Dispatcher.BeginInvoke);
                        if (!String.IsNullOrEmpty(p.Description))
                        {
                            control.Descriotion = p.Description;
                        }
                        else
                        {
                            control.Descriotion = "";
                        }

                        control.OnLineStatus = p.OnlineStatus == 1;
                        sp.Children.Add(control);
                        if (index % 2 == 0)
                        {
                            spPeople.Children.Add(sp);
                        }
                        index++;

                    }
                    //如果只有一个用户，则需要增加一个隐藏控件，用于确保panel中的控件为双数。
                    if (sp.Children.Count == 1)
                    {
                        sp.Children.Add(new StackPanel() { Width = width / 2d - gap});
                    }
                }
                ResetRefreshControl();
                //还有下一页数据
                if (cursor > 0)
                {
                    btnGetMore.Content = "点击获取更多...";
                    spPeople.Children.Add(spGetMore);
                }
                isUpdating = false;
            });
        }

        private void GetMorePeople_Click(object sender, RoutedEventArgs e)
        {
            GetPeople();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(tbSearch.Text.Trim()))
            {
                GetPeopleByName(tbSearch.Text);
            }
            else
            {
                spPeople.Children.Clear();
                EnableRefreshControl();
                cursor = 0;
                GetPeople();
            }
        }
    }
}